<template>
    <div class="virtual-list-box">
        <div class="virtual-box-header">
            <a-checkbox @change="onSelectAll">{{selected.length + '/' + dataSource.length}}项</a-checkbox>
        </div>
        <div class="virtual-box-content" @scroll="handleScroll">
            <div class="virtual-box" :style="{height: boxHeight}"></div>
            <div class="virtual-list" :style="{top: listTop}">
                <div class="list-item" v-for="item in showList" :key="item.id">
                    <a-checkbox @change="onSelect(item)">{{item.name}}</a-checkbox>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: "vVirtualList",
    data() {
        return {
            listState: {
                start: 0,
                scrollTop: [],
            },
            selected: []
        }
    },
    props: {
        listConfig: {
            type: Object,
            default: () => ({
                count: 20,
                itemHeight: 32
            })
        },
        dataSource: {
            type: Array,
            default: () => []
        }
    },
    computed: {
        showList() {
            return this.dataSource.slice(this.listState.start, this.listState.start + this.listConfig.count);
        },
        boxHeight() {
            return this.dataSource.length * this.listConfig.itemHeight + 'px';
        },
        listTop() {
            return this.listState.scrollTop + 'px'
        }
    },
    methods: {
        handleScroll(e) {
            this.listState.scrollTop = e.target.scrollTop;
            this.listState.start = parseInt(this.listState.scrollTop / this.listConfig.itemHeight, 10);
        },
        onSelect() {
            return
        },
        onSelectAll() {
            return
        }
    },
}
</script>

<style lang="less" scoped>
.virtual-list-box{
    display: flex;
    flex-direction: column;
    width: 300px;
    height: 500px;
    border: 1px solid #e8e8e8;
    border-radius: 2px;
    .virtual-box-header{
        height: 45px;
        padding: 0 12px;
        font-size: 16px;
        line-height: 45px;
        border-bottom: 1px solid #e8e8e8;
    }
    .virtual-box-content{
        flex: 1;
        overflow: auto;
        position: relative;
        padding: 12px;
        .virtual-list{
            position: absolute;
            top: 0;
            .list-item{
                height: 36px;
                line-height: 36px;
            }
        }
    }
}
</style>